#include "livewindow.h"
#include <QCloseEvent>
#include <QKeyEvent>
#include <QResizeEvent>
#include <utility>

LiveWindow::LiveWindow(QWidget* parent, Qt::WindowFlags f) : QWidget { parent, f } { }

void LiveWindow::setCurrent(int current)
{
    if (current > -1 && current < views_.size()) {
        current_ = current;
        views_.at(current)->raise();
    }
}

void LiveWindow::addView(QWidget* view, const QString& label)
{
    Q_UNUSED(label)
    current_ = views_.size();
    views_.push_back(view);
    view->setParent(this);
    if (testAttribute(Qt::WA_WState_Visible))
        view->show();
    view->raise();
}

void LiveWindow::resizeEvent(QResizeEvent* event)
{
    QWidget::resizeEvent(event);

    for (auto p : std::as_const(views_)) {
        p->resize(event->size());
    }
}

void LiveWindow::closeEvent(QCloseEvent* event)
{
    event->ignore();
    hide();
}

void LiveWindow::keyPressEvent(QKeyEvent* event)
{
    if (!views_.empty() && event->matches(QKeySequence::SelectNextPage)) {
        current_ = ++current_ % views_.size();
        views_.at(current_)->raise();
        event->accept();
    } else {
        QWidget::keyPressEvent(event);
    }
}
